﻿namespace PreGUI.Helpers
{
    using PreGUI.Attributes;
    using PreGUI.Interfaces;
    using System.Linq;
    using UnityEngine;
    using UnityEngine.Events;
    using UnityEngine.EventSystems;

    /// <summary>
    /// Internal helper extensions for PreGui.
    /// </summary>
    public static class PreGUIExtensions
    {
        public static void CallEventAction<T>(this object viewModel, string controlName, T source)
            where T : class, new()
        {
            var eventsToCall = viewModel
                .GetType()
                .GetMethods()
                .Where(x => x.GetCustomAttributes(typeof(ButtonClickEventAttribute), false).Any(z => ((ButtonClickEventAttribute)z).ControlName == controlName));

            foreach (var ev in eventsToCall)
            {
                ev.Invoke(viewModel, new object[] { source });
            }

        }

        public static void UpdateControlValue<T>(this object viewModel, string controlName, T newValue)
        {
            var members = viewModel
                .GetType()
                .GetProperties()
                .Where(x => x.GetCustomAttributes(typeof(ControlValueTargetAttribute), false).Any(z => ((ControlValueTargetAttribute)z).ControlName == controlName));

            foreach (var member in members)
            {
                member.SetValue(viewModel, newValue, null);
            }
        }

        public static void BindTo<T>(this T thisControl, string controlName, object viewModel)
            where T : IPGControl
        {
            var members = viewModel
                .GetType()
                .GetProperties()
                .Where(x => x.GetCustomAttributes(typeof(BindControlAttribute), false).Any(z => ((BindControlAttribute)z).ControlName == controlName));

            foreach (var member in members)
            {
                member.SetValue(viewModel, thisControl, null);
            }
        }


    }
}